import React, { useState, useEffect } from 'react';
import { Button, Table, Select, Space, Alert, Spin, message } from 'antd';
import { EyeOutlined, DatabaseOutlined } from '@ant-design/icons';
import { previewDataSourceData } from '@/services/dataSourceField';
import { request } from '@umijs/max';

interface DataSourceTable {
  name: string;
  comment?: string;
  row_count?: number;
}

interface DataSourceTablesResponse {
  tables: DataSourceTable[];
  total_count: number;
}

interface DataSourcePreviewProps {
  dataSourceId: number;
  dataSourceType: string;
}

const DataSourcePreview: React.FC<DataSourcePreviewProps> = ({
  dataSourceId,
  dataSourceType,
}) => {
  const [tables, setTables] = useState<DataSourceTable[]>([]);
  const [selectedTable, setSelectedTable] = useState<string>('');
  const [previewData, setPreviewData] = useState<any>(null);
  const [tablesLoading, setTablesLoading] = useState(false);
  const [previewLoading, setPreviewLoading] = useState(false);

  // 获取表列表
  const fetchTables = async () => {
    if (dataSourceType === 'CSV') {
      // CSV文件没有表的概念，直接预览
      setSelectedTable('csv_data');
      return;
    }

    setTablesLoading(true);
    try {
      const response: DataSourceTablesResponse = await request(
        `/api/data-sources/${dataSourceId}/tables`,
        {
          method: 'GET',
        }
      );
      setTables(response.tables);
      if (response.tables.length > 0) {
        setSelectedTable(response.tables[0].name);
      }
    } catch (error: any) {
      message.error(error.message || '获取表列表失败');
    } finally {
      setTablesLoading(false);
    }
  };

  // 预览数据
  const handlePreviewData = async () => {
    if (!selectedTable && dataSourceType !== 'CSV') {
      message.warning('请先选择要预览的表');
      return;
    }

    setPreviewLoading(true);
    try {
      const params: any = { limit: 20 };
      if (selectedTable && dataSourceType !== 'CSV') {
        params.table_name = selectedTable;
      }

      const preview = await request(`/api/data-sources/${dataSourceId}/preview`, {
        method: 'GET',
        params,
      });
      setPreviewData(preview);
    } catch (error: any) {
      message.error(error.message || '预览数据失败');
    } finally {
      setPreviewLoading(false);
    }
  };

  useEffect(() => {
    fetchTables();
  }, [dataSourceId, dataSourceType]);

  // 构建表格列
  const columns = previewData?.columns?.map((col: string, index: number) => ({
    title: col,
    dataIndex: index,
    key: index,
    ellipsis: true,
    width: 150,
  })) || [];

  // 构建表格数据
  const dataSource = previewData?.data?.map((row: any[], index: number) => ({
    key: index,
    ...row.reduce((acc, cell, cellIndex) => {
      acc[cellIndex] = cell;
      return acc;
    }, {} as any),
  })) || [];

  return (
    <div>
      <Space direction="vertical" style={{ width: '100%' }}>
        {/* 表选择器 */}
        {dataSourceType !== 'CSV' && (
          <div>
            <Space>
              <DatabaseOutlined />
              <span>选择表：</span>
              <Select
                style={{ width: 200 }}
                placeholder="请选择表"
                value={selectedTable}
                onChange={setSelectedTable}
                loading={tablesLoading}
                options={tables.map(table => ({
                  label: (
                    <div>
                      <div>{table.name}</div>
                      {table.comment && (
                        <div style={{ fontSize: '12px', color: '#666' }}>
                          {table.comment}
                        </div>
                      )}
                      {table.row_count !== null && (
                        <div style={{ fontSize: '12px', color: '#999' }}>
                          约 {table.row_count} 行
                        </div>
                      )}
                    </div>
                  ),
                  value: table.name,
                }))}
              />
            </Space>
          </div>
        )}

        {/* 预览按钮 */}
        <div>
          <Button
            type="primary"
            icon={<EyeOutlined />}
            onClick={handlePreviewData}
            loading={previewLoading}
            disabled={!selectedTable && dataSourceType !== 'CSV'}
          >
            预览数据
          </Button>
        </div>

        {/* 预览结果 */}
        {previewData && (
          <div>
            <Alert
              message={
                <div>
                  <strong>预览信息：</strong>
                  {previewData.table_name && (
                    <span>表名: {previewData.table_name} | </span>
                  )}
                  <span>总行数: {previewData.total_rows} | </span>
                  <span>预览行数: {previewData.sample_rows}</span>
                </div>
              }
              type="info"
              style={{ marginBottom: 16 }}
            />

            <Table
              columns={columns}
              dataSource={dataSource}
              pagination={false}
              scroll={{ x: 'max-content', y: 400 }}
              size="small"
              bordered
              loading={previewLoading}
            />
          </div>
        )}

        {/* 空状态 */}
        {!previewData && !previewLoading && (
          <div style={{ textAlign: 'center', padding: '40px 0', color: '#999' }}>
            暂无数据，请点击"预览数据"按钮
          </div>
        )}
      </Space>
    </div>
  );
};

export default DataSourcePreview;
